package org.geekbang.time.mathbasicthought.lesson7_permutate;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;

public class HorseRacing {
    public static HashMap<String, Double> q_horses_time = new HashMap<>() {
        {
            put("q1", 1.0);
            put("q2", 2.0);
            put("q3", 3.0);
        }
    };

    public static HashMap<String, Double> t_horses_time = new HashMap<>() {
        {
            put("t1", 1.5);
            put("t2", 2.5);
            put("t3", 3.5);
        }
    };

    public static ArrayList<String> q_horses = new ArrayList<>(Arrays.asList("q1", "q2", "q3"));

    public static void main(String[] args) {
        ArrayList<String> horses = new ArrayList<>(Arrays.asList("t1", "t2", "t3"));
        permutate(horses, new ArrayList<>());
    }

    public static void permutate(ArrayList<String> horses, ArrayList<String> result) {
        // 所有马匹都已经出战，判断哪方获胜，输出结果
        if (horses.size() == 0) {
            System.out.println(result);
            compare(result, q_horses);
            System.out.println();
            return;
        }

        for (int i = 0; i < horses.size(); i++) {
            // 从剩下的未出战马匹中，选择一匹，加入结果
            ArrayList<String> newResult = (ArrayList<String>) result.clone();
            newResult.add(horses.get(i));

            // 将已选择的马匹，从未出战的列表中删除
            ArrayList<String> restHorses = (ArrayList<String>) horses.clone();
            restHorses.remove(i);

            // 递归调用，对于剩余的马匹继续生成排列
            permutate(restHorses, newResult);
        }
    }

    private static void compare(ArrayList<String> result, ArrayList<String> q_horses) {
        int t_won_cnt = 0;
        for (int i = 0; i < result.size(); i++) {
            System.out.println(t_horses_time.get(result.get(i)) + " " + q_horses_time.get(q_horses.get(i)));
            if (t_horses_time.get(result.get(i)) < q_horses_time.get(q_horses.get(i))) {
                t_won_cnt++;
            }
        }

        if (t_won_cnt > (result.size() / 2))
            System.out.println("田忌获胜！");
        else
            System.out.println("齐王获胜！");

        System.out.println();
    }
}
